//
//  WCNChoosePageBtn.m
//  WCN
//
//  Created by 陈武琦 on 16/3/16.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#define kViewWidth self.frame.size.width
static const CGFloat kAnimationTime = 0.35f;

#import "WCNChoosePageView.h"

@interface WCNChoosePageView()
//选择线
@property (strong, nonatomic) UIView *line;
@property(nonatomic, strong)UIButton *selectedBtn;


@end



@implementation WCNChoosePageView
- (instancetype)initWithFrame:(CGRect)frame titles:(NSArray *)titles {

    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        [self setUpControlWithTitles:titles];
    }

    return self;

}

- (void)setUpControlWithTitles:(NSArray *)titles {
    
    [titles enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (!*stop) {
            
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            if (titles.count > 3) {
                
                [btn setFrame:CGRectMake(idx*kViewWidth/3, 0, kViewWidth/3, 40)];
            }else {
                
                [btn setFrame:CGRectMake(idx*self.frame.size.width/titles.count, 0, kViewWidth/titles.count, 40)];
            }
            btn.tag = idx + 100;
            btn.titleLabel.font = [UIFont systemFontOfSize:17];
            [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
            [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(selectPage:) forControlEvents:UIControlEventTouchUpInside];
            [btn setTitle:obj forState:UIControlStateNormal];
            [self addSubview:btn];
            if (idx == titles.count - 1) {
                self.contentSize = CGSizeMake(CGRectGetMaxX(btn.frame), self.frame.size.height);
            }
        }
    
    }];
    _line = [UIView new];
    _line.backgroundColor = [UIColor orangeColor];
    if (titles.count > 3) {
        
        [_line setFrame:CGRectMake(0, self.frame.size.height - 1, kViewWidth/3, 1)];
    }else {
        [_line setFrame:CGRectMake(0, self.frame.size.height - 1, kViewWidth/titles.count, 1)];
    
    }
    [self addSubview:_line];

}

#pragma mark - 点击分页按钮
- (void)selectPage:(UIButton *)button {
    if (self.choosePageBlock) {
        self.choosePageBlock(button.tag -100);
    }

    button.selected = YES;
    button.enabled = NO;
    if (!(self.selectedBtn.tag == button.tag)) {
        self.selectedBtn.selected = NO;
        self.selectedBtn.enabled = YES;
        self.selectedBtn = button;
    }
    __block CGRect frame = self.line.frame;
    frame.origin.x = frame.size.width*(button.tag - 100);
        
        [UIView animateWithDuration:kAnimationTime animations:^{
            self.line.frame = frame;
            
    }];
    
}




@end
